<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>发布商品 - 网上跳蚤市场</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" th:href="@{/css/style.css}" />
</head>
<body>
<div th:replace="layout :: .nav"></div>
<div class="container">
    <section>
        <h2>发布新商品</h2>

        <div class="card">
            <form id="publishForm">
                <div class="form-group">
                    <label for="name">商品名称 <span class="required">*</span></label>
                    <input type="text" id="name" name="name" required>
                </div>

                <div class="form-group">
                    <label for="description">商品描述</label>
                    <textarea id="description" name="description" rows="5"></textarea>
                </div>

                <div class="form-group">
                    <label for="price">价格 (元) <span class="required">*</span></label>
                    <input type="number" id="price" name="price" step="0.01" min="0.01" required>
                </div>

                <div class="form-group">
                    <label for="quantity">数量 <span class="required">*</span></label>
                    <input type="number" id="quantity" name="quantity" min="1" value="1" required>
                </div>

                <div class="form-group">
                    <label for="categoryId">商品分类</label>
                    <select id="categoryId" name="categoryId">
                        <option value="">-- 选择分类 --</option>
                        <!-- 分类将通过JavaScript加载 -->
                    </select>
                </div>

                <div class="form-group">
                    <label for="validUntil">有效期至 (留空表示永久有效)</label>
                    <input type="datetime-local" id="validUntil" name="validUntil">
                </div>

                <div class="form-group">
                    <label for="productImage">商品图片 (可选)</label>
                    <input type="file" id="productImage" name="productImage" accept="image/*">
                    <div class="image-preview-container hidden">
                        <img id="imagePreview" class="hidden" alt="图片预览" />
                    </div>
                </div>

                <div class="form-group">
                    <label for="imageUrl">商品图片URL (可选)</label>
                    <input type="url" id="imageUrl" name="imageUrl" placeholder="http://example.com/image.jpg">
                    <small>您可以上传图片或提供图片URL，如果两者都提供，将优先使用上传的图片</small>
                </div>

                <div class="form-actions">
                    <button type="submit" class="btn">发布商品</button>
                    <a href="/my-products" class="btn secondary">返回</a>
                </div>
            </form>
        </div>

        <div id="msg"></div>
    </section>
</div>
<script>
    // 加载分类数据
    async function loadCategories() {
        try {
            const res = await fetch('/api/categories');
            const categories = await res.json();

            const select = document.getElementById('categoryId');
            categories.forEach(category => {
                const option = document.createElement('option');
                option.value = category.id;
                option.textContent = category.name;
                select.appendChild(option);
            });
        } catch (e) {
            console.error('加载分类失败:', e);
            document.getElementById('msg').innerHTML = '<div class="error-msg">加载分类失败，请刷新页面重试</div>';
        }
    }

    // 图片预览功能
    document.getElementById('productImage').addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(event) {
                const imgPreview = document.getElementById('imagePreview');
                imgPreview.src = event.target.result;
                imgPreview.classList.remove('hidden');

                // 显示预览容器
                document.querySelector('.image-preview-container').classList.remove('hidden');
            };
            reader.readAsDataURL(file);
        }
    });

    // 发布商品
    document.getElementById('publishForm').addEventListener('submit', async function(e) {
        e.preventDefault();

        const msg = document.getElementById('msg');
        msg.innerHTML = '<div class="info-msg">正在处理，请稍候...</div>';

        // 获取表单数据
        const formData = new FormData(this);
        const productData = {
            name: formData.get('name'),
            description: formData.get('description'),
            price: parseFloat(formData.get('price')),
            quantity: parseInt(formData.get('quantity')),
            imageUrl: formData.get('imageUrl') || null
        };

        // 处理分类
        if (formData.get('categoryId')) {
            productData.category = { id: parseInt(formData.get('categoryId')) };
        }

        // 处理有效期
        if (formData.get('validUntil')) {
            productData.validUntil = new Date(formData.get('validUntil')).toISOString();
        }

        try {
            // 先处理图片上传（如果有）
            const imageFile = document.getElementById('productImage').files[0];
            if (imageFile) {
                const imageFormData = new FormData();
                imageFormData.append('file', imageFile);

                const uploadRes = await fetch('/api/upload/image', {
                    method: 'POST',
                    credentials: 'include',
                    body: imageFormData
                });

                if (!uploadRes.ok) {
                    throw new Error('图片上传失败');
                }

                const uploadData = await uploadRes.json();
                if (uploadData.imageUrl) {
                    productData.imageUrl = uploadData.imageUrl;
                } else if (uploadData.error) {
                    throw new Error(uploadData.error);
                }
            }

            // 发布商品
            const res = await fetch('/api/products/publish', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                credentials: 'include',
                body: JSON.stringify(productData)
            });

            const data = await res.json();

            if (data.error) {
                msg.innerHTML = `<div class="error-msg">${data.error}</div>`;
            } else {
                msg.innerHTML = '<div class="success-msg">商品发布成功，等待审核</div>';
                // 清空表单
                document.getElementById('publishForm').reset();
                document.getElementById('imagePreview').classList.add('hidden');

                // 延迟跳转
                setTimeout(() => {
                    window.location.href = '/my-products';
                }, 2000);
            }
        } catch (e) {
            console.error('发布商品失败:', e);
            msg.innerHTML = `<div class="error-msg">发布失败: ${e.message}</div>`;
        }
    });

    // 页面加载时加载分类
    loadCategories();
</script>
<style>
    .form-group {
        margin-bottom: 20px;
    }

    .form-actions {
        margin-top: 30px;
        display: flex;
        gap: 10px;
    }

    .required {
        color: var(--error-color);
    }

    .image-preview-container {
        margin-top: 10px;
        max-width: 300px;
    }

    #imagePreview {
        width: 100%;
        border-radius: 4px;
        border: 1px solid var(--border-color);
    }

    small {
        display: block;
        margin-top: 5px;
        color: var(--text-secondary);
    }
</style>
</body>
</html>